from flask import Flask, render_template, request, redirect, url_for
import subprocess

app = Flask(__name__)

def get_available_wifi_networks():
    # Use nmcli to list available WiFi networks
    result = subprocess.run(['nmcli', '-t', '-f', 'SSID', 'dev', 'wifi'], capture_output=True, text=True)
    ssids = result.stdout.strip().split('\n')
    return [ssid for ssid in ssids if ssid]

@app.route('/', methods=['GET', 'POST'])
def index():
    available_ssids = get_available_wifi_networks()
    if request.method == 'POST':
        ssid = request.form.get('ssid')
        password = request.form.get('password')
        connect_to_wifi(ssid, password)
        return redirect(url_for('index'))
    return render_template('index.html', available_ssids=available_ssids)


def connect_to_wifi(ssid, password):
    # Use nmcli to connect to the WiFi
    subprocess.run(['nmcli', 'dev', 'wifi', 'connect', ssid, 'password', password])

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000) 